/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package validators;

import beans.Usuario;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import rn.UsuarioRN;

/**
 *
 * @author Caio
 */
@FacesValidator("validators.ValidatorEmail")
public class ValidatorEmail implements Validator{
    
    private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    
    private final Pattern pattern;
    private Matcher matcher;
 
    public ValidatorEmail(){
        pattern = Pattern.compile(EMAIL_PATTERN);
    }

    @Override
    public void validate(FacesContext fc, UIComponent uic, Object o) throws ValidatorException {
        UsuarioRN rn = new UsuarioRN();
        List<Usuario> list = rn.buscaPersonalizada("email", (String) o);
        if(list.isEmpty()) {
            matcher = pattern.matcher(o.toString());
            if(!matcher.matches()){
		throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,"Validação de e-mail falhou", "Formato de e-mail inválido"));
            }
        } else {
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,"Validação de e-mail falhou", "E-mail em uso"));
        }
        list.clear();
    }
    
}
